package com.xci.platform.auth.controller;

import com.xci.platform.auth.entity.DicDetailsEntity;
import com.xci.platform.auth.entity.DicEntity;
import com.xci.platform.auth.service.DicDetailsService;
import com.xci.platform.auth.service.DicService;
import com.xci.platform.core.Constant;
import com.xci.platform.annotation.Authorize;
import com.xci.platform.core.BoolMessage;
import com.xci.platform.core.Tree;
import com.xci.platform.core.TreeNode;
import com.xci.platform.core.TreeNodeIndex;
import com.xci.platform.helper.ExcelHelper;
import com.xci.platform.helper.StringHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 系统字典明细控制器
 */
@Authorize
@Slf4j
@Controller
@RequestMapping("/auth/dicdetails")
public class DicDetailsController extends AuthBaseController {
    /**
     * 系统字典服务
     */
    @Resource
    protected DicService dicService;

    /**
     * 系统字典明细服务
     */
    @Resource
    protected DicDetailsService dicDetailsService;

    //region 页面视图

    /**
     * 字典明细首页
     */
    @GetMapping("/{dicCode}")
    public String index(@PathVariable String dicCode, ModelMap map) {
        if (StringHelper.isBlank(dicCode)) return notFound();
        map.put("dicCode", dicCode);
        map.put("dicName", dicService.queryNameByCode(dicCode));
        return "auth/dicdetails/index";
    }

    /**
     * 字典明细新建页面
     */
    @GetMapping("/create")
    @Authorize(code = "")
    public String create(String parentId, String dicId, String dicCode, ModelMap map) {
        createMark(map);
        DicDetailsEntity entity = new DicDetailsEntity();
        entity.setId(StringHelper.guid());
        entity.setParentId(parentId);
        if (StringHelper.isNotBlank(dicId)) {
            entity.setDicId(dicId);
            entity.setDicName(getDicName(dicId));
        } else if (StringHelper.isNotBlank(dicCode)) {
            DicEntity dicEntity = dicService.queryByCode(dicCode);
            if (dicEntity == null) {//如果找不到指定的数据字典,自动添加
                dicEntity = new DicEntity();
                dicEntity.setId(StringHelper.guid());
                dicEntity.setParentId(Constant.RootNodeId);
                dicEntity.setCode(dicCode);
                dicEntity.setName(dicCode);
                dicService.save(dicEntity, true);
            }
            entity.setDicId(dicEntity.getId());
            entity.setDicName(dicEntity.getName());
        }
        entity.setStatus(1);
        map.put("entity", entity);
        map.put("parentName", getParentName(parentId));
        return "auth/dicdetails/edit";
    }

    /**
     * 字典明细编辑页面
     */
    @GetMapping("/edit")
    @Authorize(code = "")
    public String edit(String id, ModelMap map) {
        DicDetailsEntity entity = dicDetailsService.queryById(id);
        if (entity == null) return notFound();
        map.put("entity", entity);
        map.put("parentName", getParentName(entity.getParentId()));
        return "auth/dicdetails/edit";
    }

    private String getParentName(String id) {
        String parentName = Constant.Empty;
        if (StringHelper.isNotBlank(id) && !id.equals(Constant.RootNodeId)) {
            parentName = dicDetailsService.queryNameById(id);
        }
        if (StringHelper.isBlank(parentName)) {
            parentName = "顶层";
        }
        return parentName;
    }

    private String getDicName(String dicId) {
        String dicName = Constant.Empty;
        if (StringHelper.isNotBlank(dicId) && !dicId.equals(Constant.RootNodeId)) {
            dicName = dicService.queryNameById(dicId);
        }
        return dicName;
    }

    /**
     * 字典明细详细页面
     */
    @GetMapping("/details")
    public String details(String id, ModelMap map) {
        DicDetailsEntity entity = dicDetailsService.queryById(id);
        if (entity == null) return notFound();
        map.put("entity", entity);
        return "auth/dicdetails/details";
    }

    //endregion

    //region 数据处理

    /**
     * 字典明细Tree
     */
    @ResponseBody
    @GetMapping("/tree")
    public Object tree(@RequestParam Map<String, String> params) {
        String dicCode = params.get("dicCode");
        List<Tree> list = dicDetailsService.queryTreeModelList(dicCode,1);
        return BoolMessage.tree(list);
    }

    /**
     * 字典明细表格数据
     */
    @ResponseBody
    @GetMapping("/grid")
    @Authorize(code = "")
    public Object grid(@RequestParam Map params) {
        List<DicDetailsEntity> list = dicDetailsService.query(params);
        return BoolMessage.grid(list);
    }

    /**
     * 保存新增字典明细
     */
    @ResponseBody
    @PostMapping("/create-save")
    @Authorize(code = "")
    public BoolMessage createSave(@ModelAttribute DicDetailsEntity entity ) {
        return dicDetailsService.save(entity, true);
    }

    /**
     * 保存修改字典明细
     */
    @ResponseBody
    @PostMapping("/edit-save")
    @Authorize(code = "")
    public BoolMessage editSave(@ModelAttribute DicDetailsEntity entity ) {
        return dicDetailsService.save(entity, false);
    }

    /**
     * 保存拖拽数据(父节点和路径)
     */
    @ResponseBody
    @PostMapping("/dnd")
    @Authorize(code = "")
    public BoolMessage dnd(@RequestBody TreeNodeIndex[] nodeIndexs) {
        return dicDetailsService.updateNodeIndex(nodeIndexs);
    }

    /**
     * 修改字典明细启用状态
     */
    @ResponseBody
    @PostMapping("/status")
    @Authorize(code = "")
    public BoolMessage status(String id, Integer status) {
        return dicDetailsService.updateStatus(id, status);
    }

    /**
     * 删除字典明细
     */
    @ResponseBody
    @PostMapping("/delete")
    @Authorize(code = "")
    public BoolMessage delete(String id) {
        return dicDetailsService.delete(id);
    }

    /**
     * 导出字典明细
     */
    @GetMapping("/export")
    @Authorize(code = "")
    public void export(@RequestParam Map<String, String> params, HttpServletResponse response) throws IOException {
        String dicId = params.get("dicId");
        String dicCode = params.get("dicCode");
        String title = "系统字典明细";
        DicEntity dicEntity = null;
        if (StringHelper.isNotBlank(dicId)) {
            dicEntity = dicService.queryById(dicId);
        } else if (StringHelper.isNotBlank(dicCode)) {
            dicEntity = dicService.queryByCode(dicCode);
        }
        if (dicEntity != null) {
            title = StringHelper.format("{}-{}", title, dicEntity.getName());
        }
        ExcelHelper.exportWeb(response, dicDetailsService.query(params), DicDetailsEntity.class, title);
    }

    /**
     * 查询字典明细列表
     */
    @ResponseBody
    @GetMapping("/queryListByDicCode/{dicCode}")
    public BoolMessage queryListByDicCode(@PathVariable String dicCode) {
        if (StringHelper.isBlank(dicCode)){
            return BoolMessage.fail("请指定数据字典编码");
        }
        return new BoolMessage<>(dicDetailsService.querySimpleByDicCode(dicCode));
    }

    /**
     * 查询字典明细树列表
     */
    @ResponseBody
    @GetMapping("/queryTreeByDicCode/{dicCode}")
    public Object queryTreeByDicCode(@PathVariable String dicCode) {
        if (StringHelper.isBlank(dicCode)){
            return BoolMessage.fail("请指定数据字典编码");
        }
        List<DicDetailsEntity> list = dicDetailsService.queryByDicCode(dicCode);
        List<TreeNode> models = dicDetailsService.convertToNodeList(list);
        return BoolMessage.tree(models);
    }

    //endregion
}
